﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NRCP.BusinessLogicLayer;
using NRCP.BusinessEntities;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text.html.simpleparser;
using System.Globalization;

namespace NRCP
{
    public partial class report_plan_summary : System.Web.UI.Page
    {
        private Int32 _PLAN_ID
        {
            get
            {
                return Convert.ToInt32(ViewState["_PLAN_ID"]);
            }
            set
            {
                ViewState["_PLAN_ID"] = value;
            }
        }

        private String _PLAN_YEAR
        {
            get
            {
                return ViewState["_PLAN_YEAR"].ToString();
            }
            set
            {
                ViewState["_PLAN_YEAR"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }
       
        protected void lnbShow_Click(object sender, EventArgs e)
        {
            NationalPlanBLL bll = new NationalPlanBLL();
            NationalPlan plan = bll.GetNationalPlanById(Convert.ToInt32(ddlNationalPlanYear.SelectedItem.Value));
            if (plan != null)
            {
                _PLAN_ID = plan.Id;
                _PLAN_YEAR = plan.PlanYear.ToString();
                
                if (ddlSummaryType.SelectedItem.Value == "1")
                {
                    LoadNationalPlan(plan);
                }
                else
                {
                    LoadZonalPlan(plan);                
                }
            }
        }

        #region Display Report

        private void LoadData()
        {
            NationalPlanBLL bll = new NationalPlanBLL();

            ddlNationalPlanYear.DataSource = bll.GetAllNationalPlans();
            ddlNationalPlanYear.DataTextField = "PlanYear";
            ddlNationalPlanYear.DataValueField = "Id";

            ddlNationalPlanYear.DataBind();

            //var months = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames.TakeWhile(m => m != String.Empty).Select((m, i) => new { Month = i + 1, MonthName = m }).ToList();
            //ddlMonths.DataSource = months;
            //ddlMonths.DataTextField = "MonthName";
            //ddlMonths.DataValueField = "Month";
            //ddlMonths.DataBind();

            DivisionBLL divisionBLL = new DivisionBLL();
            ddlDivision.DataSource = divisionBLL.GetAllDivisions();
            ddlDivision.DataTextField = "Name";
            ddlDivision.DataValueField = "Id";
            ddlDivision.DataBind();
        }

        private DataTable GetFormatedPlan(List<PlanSummary> summary, List<NationalPlanFish> fishes, List<NationalPlanChemicalGroup> groups)
        {
                     
            DataTable dt = new DataTable();
            DataColumn dtColumnPreDef = new DataColumn("TestParameter");
            dt.Columns.Add(dtColumnPreDef);
            foreach (var fish in fishes)
            {
                DataColumn dtColumn = new DataColumn(fish.Fish.Name);
                dt.Columns.Add(dtColumn);
            }

            foreach (var group in groups)
            {
                DataRow dr = dt.NewRow();
                dr[0] = group.ChemicalGroup.Name;
                for (int index = 1; index <= fishes.Count; index++)
                {
                    PlanSummary _planSummary = summary.FirstOrDefault(s => s.SampleGroup == group.ChemicalGroup.Name && s.SampleFish == fishes[index - 1].Fish.Name.ToString());
                    if (_planSummary != null)
                    {
                        dr[index] = _planSummary.SampleTotal;
                    }
                    else
                    {
                        dr[index] = 0;
                    }
                }
                dt.Rows.Add(dr);
            }

            return dt;
        }

        private void LoadZonalPlan(NationalPlan plan)
        {
            NationalPlanDivisionBLL divisionBll = new NationalPlanDivisionBLL();
            NationalPlanDivision planDivision = divisionBll.GetNationalPlanDivision(obj=>obj.NationalPlanId==plan.Id && obj.DivisionId==Convert.ToInt32(ddlDivision.SelectedItem.Value));

            if (planDivision != null)
            {
                List<PlanSummary> summary = GetSummary(true,planDivision.Id);
                NationalPlanFishBLL fishBLL = new NationalPlanFishBLL();
                List<NationalPlanFish> fishes = fishBLL.GetNationalPlanFishByNationalPlanId(plan.Id);

                NationalPlanChemicalGroupBLL groupBll = new NationalPlanChemicalGroupBLL();
                List<NationalPlanChemicalGroup> groups = groupBll.GetNationalPlanChemicalGroupsByNationalPlanlId(plan.Id);

                grvSampleData.DataSource = GetFormatedPlan(summary, fishes, groups);
                grvSampleData.DataBind();
                litSummaryPlanYear.Text = plan.PlanYear.ToString()+" For "+ddlDivision.SelectedItem.Text;
                pnlPlanSummary.Visible = true;
            }
         
        }

        private void LoadNationalPlan(NationalPlan plan)
        {
            List<PlanSummary> summary = GetSummary(false, null);

            NationalPlanFishBLL fishBLL = new NationalPlanFishBLL();
            List<NationalPlanFish> fishes = fishBLL.GetNationalPlanFishByNationalPlanId(plan.Id);

            NationalPlanChemicalGroupBLL groupBll = new NationalPlanChemicalGroupBLL();
            List<NationalPlanChemicalGroup> groups=groupBll.GetNationalPlanChemicalGroupsByNationalPlanlId(plan.Id);

            grvSampleData.DataSource = GetFormatedPlan(summary, fishes, groups);
            grvSampleData.DataBind();
            litSummaryPlanYear.Text = plan.PlanYear.ToString();
            pnlPlanSummary.Visible = true;
        }

        #endregion

        #region PRINT

        protected void imbPrint_Click(object sender, ImageClickEventArgs e)
        {
            if (ddlSummaryType.SelectedItem.Value == "1")
            {
                CreateSummaryPDF();
            }
            else
            {
                CreateZonalPDF();
            }
        }

        private void CreateZonalPDF()
        {
            NationalPlanDivisionBLL divisionBll = new NationalPlanDivisionBLL();
            NationalPlanDivision planDivision = divisionBll.GetNationalPlanDivision(obj => obj.NationalPlanId == _PLAN_ID && obj.DivisionId == Convert.ToInt32(ddlDivision.SelectedItem.Value));

            if (planDivision != null)
            {               
                NationalPlanFishBLL fishBLL = new NationalPlanFishBLL();
                List<NationalPlanFish> fishes = fishBLL.GetNationalPlanFishByNationalPlanId(_PLAN_ID);

                NationalPlanChemicalGroupBLL groupBll = new NationalPlanChemicalGroupBLL();
                List<NationalPlanChemicalGroup> groups = groupBll.GetNationalPlanChemicalGroupsByNationalPlanlId(_PLAN_ID);
                PdfPTable table = GetFormatedPdfPTable(GetSummary(true, planDivision.Id), fishes, groups);
                CreatePdf(table);               
            }
        }

        private void CreateSummaryPDF()
        {          

            NationalPlanFishBLL fishBLL = new NationalPlanFishBLL();
            List<NationalPlanFish> fishes = fishBLL.GetNationalPlanFishByNationalPlanId(_PLAN_ID);

            NationalPlanChemicalGroupBLL groupBll = new NationalPlanChemicalGroupBLL();
            List<NationalPlanChemicalGroup> groups = groupBll.GetNationalPlanChemicalGroupsByNationalPlanlId(_PLAN_ID);

            PdfPTable table = GetFormatedPdfPTable(GetSummary(false,null), fishes, groups);
            CreatePdf(table);
        }

        private PdfPTable GetFormatedPdfPTable(List<PlanSummary> summary, List<NationalPlanFish> fishes, List<NationalPlanChemicalGroup> groups)
        {
            PdfPTable table = new PdfPTable(fishes.Count + 1);

            PdfPCell headerCell = new PdfPCell(new Phrase("Summary Of NRCP - " + _PLAN_YEAR + @" For Shrimp, Prawn & Fish"));
            headerCell.Colspan = fishes.Count + 1;
            headerCell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
            table.AddCell(headerCell);

            PdfPCell defaultCell;
            defaultCell = new PdfPCell(new Phrase("TestParameter"));
            table.AddCell(defaultCell);

            foreach (var fish in fishes)
            {
                PdfPCell cell;
                cell = new PdfPCell(new Phrase(fish.Fish.Name));
                table.AddCell(cell);
            }



            foreach (var group in groups)
            {
                table.AddCell(group.ChemicalGroup.Name);

                for (int index = 1; index <= fishes.Count; index++)
                {
                    PlanSummary _planSummary = summary.FirstOrDefault(s => s.SampleGroup == group.ChemicalGroup.Name && s.SampleFish == fishes[index - 1].Fish.Name);
                    if (_planSummary != null)
                    {
                        table.AddCell(_planSummary.SampleTotal.ToString());
                    }
                    else
                    {
                        table.AddCell("0");
                    }
                }

            }

            return table;
        }       

        private PdfPTable GetPdfPTable(List<PlanSummary> summary, string title, bool includeTestGroup)
        {
            List<String> uniqueGroup = (from lst in summary select lst.SampleGroup).Distinct().ToList<string>();
            List<String> uniqueFish = (from lst in summary select lst.SampleFish).Distinct().ToList<string>();

            int totalColumn = uniqueFish.Count;
            if (includeTestGroup)
            {
                totalColumn = totalColumn + 1;
            }

            PdfPTable table = new PdfPTable(totalColumn);
            PdfPCell headerCell = new PdfPCell(new Phrase(title));
            headerCell.Colspan = table.NumberOfColumns;
            headerCell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
            table.AddCell(headerCell);

            if (includeTestGroup)
            {
                PdfPCell defaultCell;
                defaultCell = new PdfPCell(new Phrase("TestParameter"));
                table.AddCell(defaultCell);
            }

            foreach (var fish in uniqueFish)
            {
                PdfPCell cell;
                cell = new PdfPCell(new Phrase(fish));
                table.AddCell(cell);
            }



            foreach (var group in uniqueGroup)
            {
                if (includeTestGroup)
                {
                    table.AddCell(group);
                }

                for (int index = 1; index <= uniqueFish.Count; index++)
                {
                    PlanSummary _planSummary = summary.FirstOrDefault(s => s.SampleGroup == group && s.SampleFish == uniqueFish[index - 1].ToString());
                    if (_planSummary != null)
                    {
                        table.AddCell(_planSummary.SampleTotal.ToString());
                    }
                    else
                    {
                        table.AddCell("0");
                    }
                }

            }

            return table;
        }

        private void CreatePdf(PdfPTable table)
        {
            Document pdfDoc = new Document();
            pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
            MemoryStream memoryStream = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
            pdfDoc.Open();
            pdfDoc.Add(table);
            writer.CloseStream = false;
            pdfDoc.Close();
            memoryStream.Position = 0;
            DownloadAsPDF(memoryStream);
        }

        private void DownloadAsPDF(MemoryStream ms)
        {
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment;filename=national-plan.pdf");
            Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
            Response.OutputStream.Flush();
            Response.OutputStream.Close();
            Response.End();
            ms.Close();
        }     

        #endregion

        #region Common Functions

        private List<PlanSummary> GetSummary(bool isZonal, int? divisionId)
        {
            NationalPlanDetailsYearlyBLL yearlyBll = new NationalPlanDetailsYearlyBLL();
            if (isZonal)
            {               
                List<NationalPlanDetailsYearly> yearlies = yearlyBll.GetNationalPlanDetailsYearlys(obj => obj.NationalPlanId == _PLAN_ID && obj.DivisionId == divisionId.Value);
                var result = from y in yearlies
                             group y by new { GroupName = y.NationalPlanChemicalGroup.ChemicalGroup.Name, FishName = y.NationalPlanFish.Fish.Name } into g
                             let TotalSample = g.Sum(x => x.Count)
                             select new PlanSummary
                             {
                                 SampleFish = g.Key.FishName,
                                 SampleGroup = g.Key.GroupName,
                                 SampleTotal = TotalSample

                             };

                return result.ToList();
            }
            else
            {
                
                List<NationalPlanDetailsYearly> yearlies = yearlyBll.GetNationalPlanDetailsYearliesByNationalPlanId(_PLAN_ID);
                var result = from y in yearlies
                             group y by new { GroupName = y.NationalPlanChemicalGroup.ChemicalGroup.Name, FishName = y.NationalPlanFish.Fish.Name } into g
                             let TotalSample = g.Sum(x => x.Count)
                             select new PlanSummary
                             {
                                 SampleFish = g.Key.FishName,
                                 SampleGroup = g.Key.GroupName,
                                 SampleTotal = TotalSample

                             };

                return  result.ToList();
            }
        }

        #endregion
    }
}